package com.winit.bean.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.bean.mapper.BeanMapper;
import com.winit.bean.model.Bean;
import com.winit.bean.service.BeanService;
import com.winit.common.base.bean.ExecuteResult;
import com.winit.commons.util.SeqGenerate;
import com.winit.config.model.Config;
import com.winit.config.service.IConfigService;
import com.winit.params.service.ParamsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wanglin on 2018/6/4.
 */
@Service
public class BeanServiceImpl implements BeanService {
    @Autowired
    BeanMapper beanMapper;

    @Autowired
    private IConfigService configService;

    @Autowired
    ParamsService paramsService;

    @Override
    public Bean findByPathAndName(String path, String name){
        Map<String, Object> map = new HashMap<>();
        map.put("path",path);
        map.put("name",name);
        return beanMapper.findByPathAndName(map);
    }

    @Override
    public ExecuteResult batchSaveBean(JSONObject json) {
        JSONArray jsonArray = json.getJSONArray("models");
        if(null==jsonArray){
            return null;
        }
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            List<JSONObject> list = (List<JSONObject>) jsonObject.get("params");
            List<Bean> beans = this.saveBean(list);
            Bean bean=new Bean();
            Bean oldBean = this.findByPathAndName(jsonObject.getString("path"), jsonObject.getString("type"));
            if(oldBean != null && oldBean.getParamConfigId()!=null){
                continue;
            }
            if(oldBean==null){
                bean.setId(SeqGenerate.createId("BEAN"));
            }else{
                bean.setId(oldBean.getId());
            }
            bean.setbDesc(jsonObject.getString("remarks"));
            bean.setSys(jsonObject.getString("path").replaceAll("([\\s\\S]*)(winit\\/)([\\s\\S]*)(\\/spi\\/)([\\s\\S]*)", "$3"));
            bean.setIsBase(jsonObject.getString("isbase"));
            bean.setPath(jsonObject.getString("path"));
            bean.setName(jsonObject.getString("type"));
            Bean extendBean=null;
            //根据父类地址获取实体
            if(!StringUtils.isEmpty(json.getString("extends"))){
                extendBean = this.findByPathAndName(json.getString("extends"), null);
            }
            if(extendBean!=null){
                bean.setExtendsId(extendBean.getId());
            }
            JSONArray jsons=new JSONArray();
            for(Bean be:beans){
                JSONObject j=new JSONObject();
                j.put("beanId",be.getId());
                j.put("paramName",be.getName());
                j.put("key",be.getKey());
                j.put("value",null);
                j.put("desc",be.getbDesc());
                jsons.add(j);
            }
            Config config = new Config();
            Map<String,String> map=new HashMap<>();
            map.put("param",jsons.toJSONString());
            config.setKVMap(map);
            configService.saveConfig(config);
            bean.setParamConfigId(config.getId());
            if(oldBean==null){
                try{
                    beanMapper.insertSelective(bean);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
            }else{
                beanMapper.updateByPrimaryKeySelective(bean);
            }

        }

        return null;
    }

    @Override
    public List<JSONObject> getParam(String configId) {
        List<JSONObject> paramList=new ArrayList<>();
        if(StringUtils.isEmpty(configId)){
            return paramList;
        }
        try {
            Config config = configService.getConfigMap(configId, false);
            Map<String, String> kvMap = config.getKVMap();
            String jsonarr = kvMap.get("param");
            JSONArray jsonArr = (JSONArray) JSONArray.parse(jsonarr);
            for(int i=0;i<jsonArr.size();i++){
                JSONObject json=new JSONObject();
                JSONObject jsonA =(JSONObject) jsonArr.get(i);
                Bean bean = beanMapper.selectByPrimaryKey(jsonA.getString("beanId"));
                json.put("type",bean.getName());
                if(bean.getParamConfigId()!=null){
                    json.put("params",this.getParams(bean.getParamConfigId()));
                }
                paramList.add(json);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return paramList;
    }


    @Override
    public List<JSONObject> getRtn(String configId) {
        List<JSONObject> paramList=new ArrayList<>();
        if(StringUtils.isEmpty(configId)){
            return paramList;
        }
        try {
            Config config = configService.getConfigMap(configId, false);
            Map<String, String> kvMap = config.getKVMap();
            String jsonarr = kvMap.get("param");
            JSONObject jsonObject =(JSONObject)  JSONObject.parse(jsonarr);
            JSONObject json=new JSONObject();
            Bean bean = beanMapper.selectByPrimaryKey(jsonObject.getString("rtnBeanId"));
            json.put("type",jsonObject.get("type"));
            if(bean.getParamConfigId()!=null){
                json.put("params",this.getParams(bean.getParamConfigId()));
                if(null != jsonObject.get("contain")){
                    if("Page".equals(jsonObject.get("type"))){
//                        Page等類型
                    }
                }
                paramList.add(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paramList;
    }


    public List<JSONObject> getParams(String configId) {
        List<JSONObject> paramList=new ArrayList<>();
        try {
            Config config = configService.getConfigMap(configId, false);
            Map<String, String> kvMap = config.getKVMap();
            String jsonarr = kvMap.get("param");
            JSONArray jsonArr = (JSONArray) JSONArray.parse(jsonarr);
            for(int i=0;i<jsonArr.size();i++){
                JSONObject json=new JSONObject();
                JSONObject jsonA =(JSONObject) jsonArr.get(i);
                Bean bean = beanMapper.selectByPrimaryKey(jsonA.getString("beanId"));
                if(bean.getParamConfigId()!=null){
                    json.put("param",this.getParams(bean.getParamConfigId()));
                }
                json.put("key",jsonA.getString("key"));
                json.put("type",bean.getName());
                json.put("desc",jsonA.getString("desc"));
                paramList.add(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paramList;
    }

    public List<Bean> saveBean(List<JSONObject> params){
        List<Bean> jsons=new ArrayList<>();
        for(JSONObject param:params){
            Bean bean = new Bean();
            bean.setId(SeqGenerate.createId("BEAN"));
            bean.setName(param.getString("type"));
            if(StringUtils.isEmpty(param.getString("path"))){
                bean.setIsBase("1");
            }else{
                bean.setIsBase("0");
                bean.setPath(param.getString("path"));
                bean.setSys(param.getString("path").replaceAll("([\\s\\S]*)(winit\\/)([\\s\\S]*)(\\/spi\\/)([\\s\\S]*)", "$3"));
            }
            Bean oldBean = this.findByPathAndName(bean.getPath(), bean.getName());
            if(null == oldBean){
                beanMapper.insertSelective(bean);
            }else{
                bean.setId(oldBean.getId());
            }
            bean.setbDesc(param.getString("remarks"));
            bean.setKey(param.getString("name"));
            jsons.add(bean);
        }
        return jsons;
    }
}
